//
//  ButtonOcenController.swift
//  PoomsaeScringAll
//
//  Created by Илья Проскурнев on 29/04/2019.
//  Copyright © 2019 Илья Проскурнев. All rights reserved.
//

import UIKit
import AVFoundation
import AudioToolbox

class ButtonOcenController: UIViewController {
    
    @IBOutlet var buttonOcen: UIView!
    @IBOutlet weak var loadVist: UIActivityIndicatorView!
    
    var idhost: String?
    var phumseName: String?
    var sudNum: Int?
    var kolSud: Int?
    var sys: Int!
    var kort: Int?
    
    var canBtn01, canBtn03: Int?
    
    @IBOutlet weak var minus01: UIButton!
    @IBOutlet weak var minus03: UIButton!
    var URL_VISTUP: String?
    let URL_VISTUPLENIE2 = "/php_isap/vistup/vistuplenie.php"
    
    var URL_SUD: String?
    let URL_SUD2 = "/php_isap/sud/sudi.php"
    
    var URL_SUDGOT: String?
    let URL_SUDGOT2 = "/php_isap/sud/sudigotov.php"
    
    @IBOutlet weak var sudNomer: UILabel!
    @IBOutlet weak var phumse: UILabel!
    
    var vistocen: Int!
    
    var idvistuplenie: Int?
    var success: Int?
    var pokaz: Int?
    
    var pr1: Int!
    var pr2: Int!
    var pr3: Int!
    
    @IBOutlet weak var can03: UIButton!
    @IBOutlet weak var res: UIButton!
    @IBOutlet weak var can01: UIButton!
    @IBOutlet weak var err01: UILabel!
    @IBOutlet weak var err03: UILabel!
    @IBOutlet weak var presentation: UIButton!
    
    @IBOutlet weak var accuracy: UILabel!
    var doubleAccuracy: Double?
    var setAccuracy: Int?
    var num03 = 0
    var num01 = 0
    var Acd = Double(0)
    
    var gotov = 0
    
    @objc func vistuplenieItem() {
        print("TUT vistup")
        let url: URL = URL(string: self.URL_VISTUP ?? "localhost")!
        print("url = ", url)
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
        
        let task = defaultSession.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print("Failed to download data")
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    self.vistuplenieItem()
                })
            } else {
                print("TUT vistup else")
                self.parseJSONVistup(data!)
            }
        }
        task.resume()
    }
    
    func parseJSONVistup(_ data:Data) {
        print("parseJSONVistup")
        var jsonResult = NSDictionary()
        do {
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
            let idvist = jsonResult["success"] as? String
            let kolVist = jsonResult["vistuplenie_pokaz"] as? String
            let phum = jsonResult["phumse"] as? String
            if (idvist != "") {
                self.idvistuplenie = Int (idvist!)!
                self.pokaz = Int (kolVist!)!
                self.phumseName = String (phum!)
            } else { self.idvistuplenie = 0 }
        } catch {
            print(error)
        }
        
        if (self.idvistuplenie != 0) {
            print("TUT0")
            sudi()
        } else {
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                self.vistuplenieItem()
            })
        }
    }
    
    @discardableResult
    func printScoring(_: String) -> String {
        
        if(num03 == 0) {
            err03.text = "0 X"
        } else {
            err03.text = String(num03) + " X"
        }
        
        if(num01 == 0) {
            err01.text = "X 0"
        } else {
            err01.text = "X " + String(num01)
        }
        
        let acc = 40 - num01 - (num03 * 3)
        if (acc<0) {
            Acd = 0
        } else {
            Acd = (Double(acc)/Double(10))
        }
        let sc = String(Acd)
        accuracy.text = sc
        return sc
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.setHidesBackButton(true, animated: true)
        // Do any additional setup after loading the view.
        can03.layer.cornerRadius = 3
        can03.layer.borderWidth = 3
        can03.layer.borderColor = UIColor.gray.cgColor
        
        can01.layer.cornerRadius = 3
        can01.layer.borderWidth = 3
        can01.layer.borderColor = UIColor.gray.cgColor
        
        res.layer.cornerRadius = 3
        res.layer.borderWidth = 3
        res.layer.borderColor = UIColor.gray.cgColor
        
        buttonOcen.isHidden = true
        printScoring(String(accuracy.text! as NSString))
        self.URL_VISTUP = self.idhost! + self.URL_VISTUPLENIE2
        self.loadVist.isHidden = false
        self.loadVist.startAnimating()
        vistuplenieItem()
    }
    
    @IBAction func cancel03(_ sender: Any) {
        if (num03>0) {
            num03=num03-1
            self.time_click()
            canBtn03 = canBtn03! + 1
        }
        printScoring(String(accuracy.text! as NSString))
    }
    @IBAction func reset(_ sender: Any) {
        num01 = 0
        num03 = 0
        printScoring(String(accuracy.text! as NSString))
    }
    @IBAction func cancel01(_ sender: Any) {
        if (num01>0) {
            num01=num01-1
            self.time_click()
            canBtn01 = canBtn01! + 1
        }
        printScoring(String(accuracy.text! as NSString))
    }
    
    override func prepare (for segue: UIStoryboardSegue, sender: Any?) {
        let presentationController: PresentationController = segue.destination as! PresentationController
        presentationController.idhost = self.idhost
        presentationController.sudNum = self.sudNum
        presentationController.idvistuplenie = self.idvistuplenie!
        presentationController.Acd = self.Acd
        presentationController.num01 = self.num01
        presentationController.num03 = self.num03
        presentationController.kolSud = self.kolSud
        presentationController.pokaz = self.pokaz
        presentationController.sys = self.sys
        presentationController.vistocen = self.vistocen
        presentationController.kort = self.kort
    }
    
    func sudi()  {
        print("TUT1")
        self.URL_SUD = self.idhost! + self.URL_SUD2
        let requestURL = NSURL(string: URL_SUD!)
        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL! as URL)
        //setting the method to post
        request.httpMethod = "POST"
        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "vistuplenie_idvistuplenie="+String(self.idvistuplenie!)+"&nomersud="+String (self.sudNum!)
        //adding the parameters to request body
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        var myJSON = NSDictionary()
        //creating a task to send the post request
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            do {
                if (error != nil) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.sudi()
                    })
                } else {
                    myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    print("myJSON = ", myJSON)
                    self.success = (myJSON["success"] as! Int?)!
                    if(self.success! > 0) {
                        print("TUT2")
                        self.sudigotov()
                    } else {
                        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                            print("TUT3")
                            self.sudi()
                        })
                    }
                }
            } catch {
                print(error)
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                     self.sudi()
                 })
            }
        }
        //executing the task
        task.resume()
    }
    
    func sudigotov()  {
        self.URL_SUDGOT = self.idhost! + self.URL_SUDGOT2
        let requestURL = NSURL(string: URL_SUDGOT!)
        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL! as URL)
        //setting the method to post
        request.httpMethod = "POST"
        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "vistuplenie_idvistuplenie=" + String (self.idvistuplenie!);
        print("postParameters = ",postParameters)
        //adding the parameters to request body
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        var myJSON = NSDictionary()
        //creating a task to send the post request
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            
            //parsing the response
            do {
                //converting resonse to NSDictionary
                if (error != nil) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.sudigotov()
                    })
                } else {
                myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    print("myJson = ",myJSON)
                }
            } catch {
                print("Tut error")
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    self.sudigotov()
                })
            }
            self.success = (myJSON["success"] as! Int?)!
            if (self.success != self.kolSud) {
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    self.sudigotov()
                })
            } else {
                DispatchQueue.main.async {
                    print("ELSE")
                    self.loadVist.stopAnimating()
                    self.loadVist.isHidden = true
                    self.buttonOcen.isHidden = false
                    self.gotov = 1
                    self.sudNomer.text = "Судья № " + String (self.sudNum!)
                    self.phumse.text = "Пхумсэ " + self.phumseName!
                }
            }
        }
        //executing the task
        task.resume()
    }
    
    
    @IBAction func btn03(_ sender: UIButton) {
        
        if(UIDevice().userInterfaceIdiom == .phone)
        {
            AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
        }
        else
        {
            AudioServicesPlayAlertSound (1105);
        }
        if (num01+num03*3 < 40) {
            num03 = num03+1
            self.time_click()
        }
        printScoring(String(accuracy.text! as NSString))
        
    }
    @IBAction func btn01(_ sender: UIButton) {
        AudioServicesPlaySystemSound(SystemSoundID(1003))
        if (num01+num03*3 < 40) {
            num01 = num01+1
            self.time_click()
        }
        printScoring(String(accuracy.text! as NSString))
    }
    
    func time_click() {
        let date = Date()
        let calendar = Calendar.current
        let minute = calendar.component(.minute, from:date)
        let second = calendar.component(.second, from: date)
        let milisecond = calendar.component(.nanosecond, from: date)
        print("minute = ", minute, "second = ", second,"nanosecond = ", milisecond,"num01 = ",num01,"num03 = ",num03)
    }

}
